package com.lxl.core;

import com.lxl.Launcher;
import com.lxl.config.TaskStatus;
import com.lxl.service.InterfaceMonitorService;
import org.pentaho.di.core.exception.KettleException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LongTaskExecutor extends TaskExecutor {
    public final static String EXECUTOR_TYPE = "long";

    private static Logger LOGGER;

    static {
        LOGGER = Logger.getLogger(Launcher.class.getName());
        LOGGER.setLevel(Level.INFO);
    }

    public LongTaskExecutor(ServletRequest request, ServletResponse response) {
        super.taskDataMeta = new TaskDataMeta(request);
    }

    @Override
    public void run() {
        String realName = EXECUTOR_TYPE + this.taskDataMeta.interfaceMonitor.getInterfaceCategory();
        this.taskDataMeta.interfaceMonitor.setInterfaceCategory(realName);

        try {
            InterfaceMonitorService.createInstance().saveOrUpdateLog(this.taskDataMeta.interfaceMonitor, false);
            if (taskDataMeta.verifyTaskEffectiveness()) {
                LOGGER.info("Inspection failed. Please check " + taskDataMeta.taskLocalConfigFileName + "'s file and url.");
                this.taskDataMeta.interfaceMonitor.setStatus(TaskStatus.ERROR);
                this.taskDataMeta.interfaceMonitor.setNote("Inspection failed.");
                InterfaceMonitorService.createInstance().saveOrUpdateLog(this.taskDataMeta.interfaceMonitor, true);
                return;
            }
            TaskResultMeta resultMeta = runTask();

            if (resultMeta.getCode() > 0) {
                LOGGER.info(taskDataMeta.taskLocalConfigFileName + " work fail.");
                this.taskDataMeta.interfaceMonitor.setStatus(TaskStatus.ERROR);
                this.taskDataMeta.interfaceMonitor.setNote("Error Code" + resultMeta.getCode());
            } else {
                LOGGER.info(taskDataMeta.taskLocalConfigFileName + " work success.");
            }

            InterfaceMonitorService.createInstance().saveOrUpdateLog(this.taskDataMeta.interfaceMonitor, true);
        } catch (KettleException e) {
            e.printStackTrace();
            this.taskDataMeta.interfaceMonitor.setStatus(TaskStatus.ERROR);
            this.taskDataMeta.interfaceMonitor.setNote(e.getMessage());
            this.taskDataMeta.interfaceMonitor.setTimeConsuming(0L);
            InterfaceMonitorService.createInstance().saveOrUpdateLog(this.taskDataMeta.interfaceMonitor, true);
        }
    }
}
